const APPID_STORAGE_KEY = "APP_ID";
const APPSECRET_STORAGE_KEY = "APP_SECRET";
const PLATFORM_URL = "https://yikeapi.com/account/reg";
const API_URL0 = "https://v0.yiketianqi.com/free/";
const API_URL1 = "https://www.yiketianqi.com/free/";

/** 删除最后一个逗号 */
function removeLastComma(str) {
  if ([",", "，"].includes(str[str.length - 1])) {
    return str.slice(0, -1);
  }
  return str;
}

function renderDetail(data) {
  let title = "";
  let desc = "";

  title += data.date ? data.date : "现在天气";
  // 天气情况
  title += `：${data.wea}，`;
  // 实时温度
  if (data.tem) title += `${data.tem}℃，`;

  // 温度(低温~高温)
  title += `${data.tem_night}℃ ~ ${data.tem_day}℃`;

  if (data.win) desc += `风向：${data.win}，`;
  if (data.win_speed) desc += `风力等级：${data.win_speed}，`;
  if (data.win_meter) desc += `风速：${data.win_meter}，`;
  if (data.air) desc += `空气质量：${data.air}，`;

  desc = removeLastComma(desc);

  return {
    title: title,
    description: desc,
  };
}

function fetchData(url, params) {
  const axios = require("axios");
  return new Promise((resolve, reject) => {
    if (!url) {
      return reject("参数不正确");
    }
    if (params) {
      url += "?" + params;
    }
    axios
      .get(url)
      .then((res) => {
        if (res && Object.keys(res)?.length && res.status === 200) {
          resolve(res.data);
        } else {
          reject();
        }
      })
      .catch((err) => {
        console.error(url + " 调用失败！", err);
        reject(err.message);
      });
  });
}

function fetch(url, params) {
  return new Promise((resolve, reject) => {
    fetchData(API_URL0 + url, params)
      .then((res) => resolve(res))
      .catch((err) => {
        // 重试另一个url
        fetchData(API_URL1 + url, params)
          .then((res2) => resolve(res2))
          .catch((err2) => reject(err2));
      });
  });
}

window.exports = {
  fyweather: {
    // 注意：键对应的是 plugin.json 中的 features.code
    mode: "list", // 列表模式
    args: {
      // 进入插件应用时调用（可选）
      enter: (action, callbackSetList) => {
        const appid = window.utools.dbStorage.getItem(APPID_STORAGE_KEY);
        const appsecret = window.utools.dbStorage.getItem(APPSECRET_STORAGE_KEY);
        if (!appid || !appsecret) {
          callbackSetList([
            {
              title: "请先设置appid和appsecret",
              description: "请在风云天气设置中进行设置",
              type: "setting",
            },
          ]);
        } else {
          callbackSetList([
            {
              title: "查询实时天气",
              description: "显示当天的天气详情",
              type: "day",
            },
            {
              title: "查询7日天气",
              description: "显示7天内的天气详情",
              type: "week",
            },
          ]);
        }
      },
      // 子输入框内容变化时被调用 可选 (未设置则无搜索)
      search: (action, searchWord, callbackSetList) => {
        const appid = window.utools.dbStorage.getItem(APPID_STORAGE_KEY);
        const appsecret = window.utools.dbStorage.getItem(APPSECRET_STORAGE_KEY);
        if (!appid || !appsecret) {
          callbackSetList([
            {
              title: "请先设置appid和appsecret",
              description: "请在风云天气设置中进行设置",
              type: "setting",
            },
          ]);
        } else {
          // 执行 callbackSetList 显示出来
          if (searchWord && searchWord.trim()) {
            callbackSetList([
              {
                title: "查询实时天气",
                description: `显示${searchWord}当天的天气详情`,
                type: "day",
                keyword: searchWord,
              },
              {
                title: "查询7日天气",
                description: `显示${searchWord}7天内的天气详情`,
                type: "week",
                keyword: searchWord,
              },
            ]);
          } else {
            callbackSetList(null);
          }
        }
      },
      // 用户选择列表中某个条目时被调用
      select: (action, itemData, callbackSetList) => {
        if (itemData.type === "setting") {
          callbackSetList([
            {
              title: "请先设置appid和appsecret",
              description: "请在风云天气设置中进行设置",
              type: "setting",
            },
          ]);
        } else if (itemData.keyword && (itemData.type === "day" || itemData.type === "week")) {
          const appid = window.utools.dbStorage.getItem(APPID_STORAGE_KEY);
          const appsecret = window.utools.dbStorage.getItem(APPSECRET_STORAGE_KEY);
          fetch(itemData.type, `appid=${appid}&appsecret=${appsecret}&unescape=1&city=${itemData.keyword || ""}`)
            .then((res) => {
              console.log("响应数据:", res);
              if (res && Object.keys(res)) {
                if (res.errmsg) {
                  callbackSetList([
                    {
                      title: "查询错误！",
                      description: res.errmsg,
                      type: "error",
                    },
                  ]);
                } else {
                  if (itemData.type === "day") {
                    const showList = [];
                    showList.push(renderDetail(res));
                    showList.push({ title: "数据更新时间：", description: res.update_time });
                    callbackSetList(showList);
                  } else if (itemData.type === "week") {
                    if (res.data && res.data.length) {
                      const showList = [];
                      res.data.forEach((obj) => {
                        showList.push(renderDetail(obj));
                      });
                      showList.push({ title: "数据更新时间：", description: res.update_time });
                      callbackSetList(showList);
                    }
                  }
                }
              }
            })
            .catch((err) => {
              console.error("天气查询失败!", err);
              utools.showNotification("天气查询失败，请输入正确的位置后重试。", "fyweather");
            });
        }
      },
      // 子输入框为空时的占位符，默认为字符串"搜索"
      placeholder: "可输入城市名称进行搜索",
    },
  },
  "fyweather-setting": {
    mode: "list", // 文档模式
    args: {
      /**
       * 进入插件应用时调用（可选）
       * @param {*} action 
         {
            code: "fyweather-setting"
            payload: "weather-setting"
            type: "text"
         }
      */
      enter: (action, callbackSetList) => {
        const appid = window.utools.dbStorage.getItem(APPID_STORAGE_KEY);
        const appsecret = window.utools.dbStorage.getItem(APPSECRET_STORAGE_KEY);
        const showList = [];
        if (appid) {
          showList.push({
            title: "已设置appid",
            description: appid,
            icon: "", // 图标(可选)
          });
        } else {
          showList.push({
            title: "请设置appid",
            description: "请输入后按回车保存appid",
          });
        }
        if (appsecret) {
          showList.push({
            title: "已设置appsecret",
            description: appsecret,
            icon: "", // 图标(可选)
          });
        } else {
          showList.push({
            title: "请设置appsecret",
            description: "请输入后按回车保存appsecret",
          });
        }
        if (!appid || !appsecret) {
          showList.push({
            title: "如果没有appid和appsecret，请先注册",
            description: "点击打开页面进行注册",
            url: PLATFORM_URL,
          });
        }
        // 如果进入插件应用就要显示列表数据
        callbackSetList(showList);
      },
      /** 子输入框内容变化时被调用 可选 (未设置则无搜索) */
      search: (action, searchWord, callbackSetList) => {
        // 获取一些数据
        // 执行 callbackSetList 显示出来
        callbackSetList([
          {
            title: "设置appid",
            description: "按回车保存",
            appid: searchWord,
          },
          {
            title: "设置appsecret",
            description: "按回车保存",
            appsecret: searchWord,
          },
          {
            title: "如果没有appid和appsecret，请先注册",
            description: "点击打开页面进行注册",
            url: PLATFORM_URL,
          },
        ]);
      },
      /**
       * 用户选择列表中某个条目时被调用
       * @param {*} action
       * @param {*} itemData 上一个操作选中的callbackSetList里面的对象
       * @param {*} callbackSetList
       */
      select: (action, itemData, callbackSetList) => {
        if (itemData.appid) {
          window.utools.dbStorage.setItem(APPID_STORAGE_KEY, itemData.appid);
          window.utools.showNotification("保存成功");
          window.utools.hideMainWindow();
        } else if (itemData.appsecret) {
          window.utools.dbStorage.setItem(APPSECRET_STORAGE_KEY, itemData.appsecret);
          window.utools.showNotification("保存成功");
          window.utools.hideMainWindow();
        } else if (itemData.url) {
          // 浏览器打开
          window.utools.shellOpenExternal(itemData.url);
        }
        // 隐藏主体窗口
        // window.utools.hideMainWindow();
        // 退出插件
        // window.utools.outPlugin();
      },
      // 子输入框为空时的占位符，默认为字符串"搜索"
      placeholder: "设置后重新进入即可查看已设置项",
    },
  },
};
